package com.rmy.common.utils.file;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class FileDownloader {
    /**
     * 下载图片，自动生成后缀名
     * @param fileUrl
     * @param saveDir
     * @throws IOException
     */
    public static void downloadFile(String fileUrl, String saveDir) throws IOException {
        URL url = new URL(fileUrl);
        URLConnection conn = url.openConnection();
        String contentType = conn.getContentType();
        String fileExt = getFileExtension(contentType);
        String fileName = getFileName(url);
        String filePath = saveDir + "/" + fileName + "." + fileExt;

        try (BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
             FileOutputStream out = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        System.out.println("文件下载完成：" + filePath);
    }

    private static String getFileExtension(String contentType) {
        if (contentType == null || contentType.isEmpty()) {
            return "";
        }

        if (contentType.contains("image/jpeg")) {
            return "jpg";
        } else if (contentType.contains("image/png")) {
            return "png";
        } else if (contentType.contains("application/pdf")) {
            return "pdf";
        } else if (contentType.contains("text/plain")) {
            return "txt";
        } else {
            // 如果无法识别文件类型，则返回默认的扩展名
            return "file";
        }
    }

    private static String getFileName(URL url) {
        String urlString = url.toString();
        return urlString.substring(urlString.lastIndexOf("/") + 1);
    }
}
